package com.yonyou.jrmob.lryapp.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.michael.selectimage.PhotoPickerActivity;
import com.yonyou.jr.mob.rzkh.R;
import com.yonyou.jrmob.lryapp.RTHelperA;
import com.yonyou.uap.um.application.ApplicationContext;
import com.yonyou.uap.um.base.UMEventArgs;
import com.yyuap.summer.StartSummerActivity;
import com.yyuap.summer.core2.SuperSummerActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.DrawableUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.StatusBarUtil;
import jrmob.yonyou.com.commonlib.baseui.base.BaseApp_lib;

//import com.yonyou.jrmob.contacts.contact.bean.ContactsVO_ct;
//import com.yonyou.jrmob.contacts.contact.constant.Constant_ct;

/**
 * Created by yanglin  on 16/8/24.
 */
public class OpenSummerActivity extends StartSummerActivity {

    //    private boolean isStart = true;
    private String mUrl = "index.html";
    private String[] photo;
    private ArrayList<String> result;

    //    private String mUrl = "http://www.baidu.com";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        ApplicationContext.getCurrent(this);
        StatusBarUtil.setStatusBarColor(this, R.color.login_titlebar);
        String url = this.getIntent().getStringExtra("url");
        String mAndroidFilePath = this.getIntent().getStringExtra(SuperSummerActivity.ANDROIDFILEPATH);
        setmAndroidFilePath(mAndroidFilePath);
        if (!TextUtils.isEmpty(url)) {
            this.mUrl = url;
        }
        LogUtils.e("AndroidFilePathUrl",mUrl);
        if (this.params == null) {
            this.params = new JSONObject();

            try {
                this.params.put("url", this.mUrl);
            } catch (JSONException var4) {
                Log.e("mmmm", "" + var4);
                var4.printStackTrace();
            }
        }

        // h5间跳转用到
        String appidversion = this.getIntent().getStringExtra("appidversion");
        String startPage = this.getIntent().getStringExtra("startPage");
        if (!TextUtils.isEmpty(appidversion) && !TextUtils.isEmpty(startPage)) {
            try {
                this.params.put("url", "../../" + appidversion + "/www/"+startPage);
            } catch (JSONException var4) {
                Log.e("mmmm", "" + var4);
                var4.printStackTrace();
            }
        }


        super.onCreate(savedInstanceState);
//        isStart = false;
        BaseApp_lib.mact = this;
    }


//    protected void onResume() {
//        super.onResume();
//
//        if (!isStart) {
//
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    SystemClock.sleep(1000);
//                    handler.sendEmptyMessage(1);
//                }
//            }).start();
//
//
//        }
//        isStart = true;
//
//        String model = LRYApplication.model;
//        if (model != null && model.startsWith("HM NOTE")){
//            refContactCallBack();
//        }
//
//
//    }


    private void refContactCallBack() {

        try {

//            //LogUtils.e("人员参照回来...");
//            ArrayList<ContactsVO_ct> list = Constant_ct.SELECT_LIST;
//            if (null != list) {
//                for (ContactsVO_ct vo : list) {
//                    vo.setCuserId(vo.getCuserId());
//                }
//            }
//            //list.clear();
//            ContactsVO_ct vo = new ContactsVO_ct();
//            vo.setCuserId("yujing@chamc.com.cn@3711");
//            vo.setContactName("丼瑜");
//            vo.setUser_email("yujing@chamc.com.cn@3711");
            //list.add(vo);

//            Gson gson = new Gson();
//            String array = gson.toJson(list);
//            UMEventArgs args = BaseApp_lib.umeventargs;

            // 适配ios
//            JSONObject json = new JSONObject();
//                json.put("result", array.toString());
//            json.put("data", array);
//            args.put("result", json.toString());

//                LogUtils.e("UMEventArgs args: " + args.toJSONObject());
//                LogUtils.e("array:\n" + array);
            // 可用接受一些参数
//            RTHelperA.execCallBack(args);

        } catch (Exception e) {

        }

    }

//    /**
//     * handler 实例
//     */
//    android.os.Handler handler = new android.os.Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//
//            super.handleMessage(msg);
//            //LogUtils.e("android.os.Handler");
//            SummerService.tokenMethod();
//
//        }
//    };


    /************************/

    public void callbackh5(Bitmap bitmap) {
        UMEventArgs args = BaseApp_lib.umeventargs;


        if (false) {
            ImageView view = new ImageView(OpenSummerActivity.this);
            view.setImageBitmap(bitmap);
            Toast toast = Toast.makeText(OpenSummerActivity.this, "", Toast.LENGTH_LONG);
            toast.setView(view);
            toast.show();
            return;
        }


        try {

            if (null == args) {
                LogUtils.e("args is null");
                Toast.makeText(OpenSummerActivity.this, "args is null", Toast.LENGTH_LONG).show();
                return;
            }

            if (bitmap == null) {
                LogUtils.e("bitmap is null");
                Toast.makeText(OpenSummerActivity.this, "bitmap is null", Toast.LENGTH_LONG).show();
                return;
            }

            JSONObject json1 = new JSONObject();

            String bitmapToBase64 = DrawableUtils.bitmapToBase64(DrawableUtils.imageZoom(bitmap));
            json1.put("photostring", bitmapToBase64);

            args.put("result", json1);

            //LogUtils.e("UMEventArgs args: " + args.toJSONObject());
            RTHelperA.execCallBack(args);

        } catch (Exception e) {
            LogUtils.e(e);
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        // 将拍摄的照片显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
//                        picture.setImageBitmap(bitmap);

//                        ImageView view = new ImageView(OpenSummerActivity.this);
//                        view.setImageBitmap(bitmap);
//                        Toast toast = Toast.makeText(OpenSummerActivity.this, "", Toast.LENGTH_LONG);
//                        toast.setView(view);
//                        toast.show();

                        callbackh5(bitmap);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    // 判断手机系统版本号
                    if (Build.VERSION.SDK_INT >= 19) {
                        // 4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data);
                    } else {
                        // 4.4以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            case CHOOSE_PHOTOS:
                // 图片选择结果回调
                if (null!=data){
                    result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                    LogUtils.e("PHOTO",result.size());
                    displayImageaArr();
                }
                break;
            default:
                break;
        }


    }


    public static final int TAKE_PHOTO = 1;
    public static final int CHOOSE_PHOTO = 2;
    private static final int CHOOSE_PHOTOS = 3;
    private ImageView picture;
    private Uri imageUri;

    public void OpenAlbum() {

        if (ContextCompat.checkSelfPermission(OpenSummerActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(OpenSummerActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            openAlbum();
        }

    }

    public void OpenAlbumArray() {

        if (ContextCompat.checkSelfPermission(OpenSummerActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(OpenSummerActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
        } else {
            openAlbumArray();
        }

    }

    public void TakePhoto() {
        // 创建File对象，用于存储拍照后的图片
        File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT < 24) {
            imageUri = Uri.fromFile(outputImage);
        } else {
            imageUri = FileProvider.getUriForFile(OpenSummerActivity.this, OpenSummerActivity.this.getPackageName() + ".fileprovider", outputImage);
        }
        // 启动相机程序
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO);
    }


    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO); // 打开相册
    }

    private void openAlbumArray() {
        //跳转图片选择
        Intent intent = new Intent(OpenSummerActivity.this, PhotoPickerActivity.class);
        intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, false);
        intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_MULTI);
        //intent.putExtra(PhotoPickerActivity.EXTRA_CROP_IMAGE, true);
        intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN,5);
        startActivityForResult(intent, CHOOSE_PHOTOS);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;
            case 2:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbumArray();
                } else {
                    Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        Log.d("TAG", "handleImageOnKitKat: uri is " + uri);
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath); // 根据图片路径显示图片
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {

            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
//            ImageView view = new ImageView(OpenSummerActivity.this);
//            view.setImageBitmap(bitmap);
//            Toast toast = Toast.makeText(OpenSummerActivity.this, "", Toast.LENGTH_LONG);
//            toast.setView(view);
//            toast.show();

            callbackh5(bitmap);

        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }

    private void displayImageaArr() {

        if (result != null && result.size() != 0) {

            photo = new String[result.size()];

            for (int i = 0; i < result.size(); i++) {
                String imagePath =result.get(i);
                if (!TextUtils.isEmpty(imagePath)) {

                    Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                    if (bitmap == null) {
                        LogUtils.e("bitmap is null");
                        Toast.makeText(OpenSummerActivity.this, "bitmap is null", Toast.LENGTH_LONG).show();
                        return;
                    }
                    String bitmapToBase64 = DrawableUtils.bitmapToBase64(DrawableUtils.imageZoom(bitmap));
                    photo[i] = bitmapToBase64;
                    bitmap.recycle();
                } else {
                    Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
                }

            }
            //传递给小程序
            UMEventArgs args = BaseApp_lib.umeventargs;
            try {
                if (null == args) {
                    LogUtils.e("args is null");
                    Toast.makeText(OpenSummerActivity.this, "args is null", Toast.LENGTH_LONG).show();
                    return;
                }
                JSONObject json1 = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                for (int i = 0;i<photo.length;i++){
                    jsonArray.put(i,photo[i]);
                }
                json1.put("photostring", jsonArray);
                args.put("result", json1);
                //LogUtils.e("UMEventArgs args: " + args.toJSONObject()+"UUUU"+jsonArray.length());
                RTHelperA.execCallBack(args);

            } catch (Exception e) {
                LogUtils.e(e);
                e.printStackTrace();
            }

        }

    }

    /************************/


}
